package org.apache.rocketmq.console.config.intercepter;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.rocketmq.console.config.RMQConfigure;
import org.apache.rocketmq.console.script.dao.OperationLogDao;
import org.apache.rocketmq.console.script.model.EnvironDic;
import org.apache.rocketmq.console.script.model.OperationLog;
import org.apache.rocketmq.console.script.service.EnvService;
import org.apache.rocketmq.console.shiro.entity.UserInfo;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class InterfaceAuthCheckInterceptor implements HandlerInterceptor {
	@Autowired
	private RMQConfigure rmqConfigure;
	@Autowired
	private OperationLogDao operationLogDao;

	@Autowired
	public EnvService envService;

	JSONObject parameterMap;
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		System.out.println("拦截器afterCompletion===============================");
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
		EnvironDic currentRegion = rmqConfigure.getCurrentRegion();
		OperationLog operationLog = new OperationLog();
		System.out.println("parameterMap=============" + parameterMap.toJSONString());
		int status = response.getStatus();
		System.out.println("status=============" + status);
		String remoteAddr = null;
		String beanName = null;
		String methodName = null;
		String uri = null;
		MethodParameter[] mps = null;
		try {
			if (handler instanceof HandlerMethod) {
				HandlerMethod handlerMethod = (HandlerMethod) handler;
				beanName = handlerMethod.getBean().getClass().toString();
				methodName = handlerMethod.getMethod().getName();
				uri = request.getRequestURI();
				remoteAddr = getIpAddr(request);
				// String sessionId = request.getSession().getId();
				// String user = (String) request.getSession().getAttribute(Constant.USER);

				mps = ((HandlerMethod) handler).getMethodParameters();
				for (MethodParameter mp : mps) {
					System.out.println(mp.getParameterName() + " --  " + mp.getParameterType());
				}
			}
			operationLog.setParameterKey(mps[0].getParameterName());
			if (parameterMap.toJSONString().length() > 255) {
				operationLog.setParameterValue(parameterMap.toJSONString().substring(0, 250));
			} else {
				operationLog.setParameterValue(parameterMap.toJSONString());
			}
			operationLog.setEnviroCode(currentRegion.getEnviroCode());
			operationLog.setEnviroName(currentRegion.getEnviroName());
			operationLog.setRegionCode(currentRegion.getRegionCode());
			operationLog.setRegionName(currentRegion.getRegionName());
			if ((beanName + "-" + methodName).length() > 255) {
				operationLog.setOpCode((beanName + "-" + methodName).substring(0, 250));
			} else {
				operationLog.setOpCode(beanName + "-" + methodName);
			}
			operationLog.setOpDate(new Date());
			// operationLog.setOpFailureReason("");
			operationLog.setOpIp(remoteAddr);
			// operationLog.setOpName(opName);
			operationLog.setOpResult("200".equals(response.getStatus() + "") ? "成功" : "失败");
			operationLog.setOpUser(userInfo.getName());
			operationLog.setOthers(uri);
			System.out.println("operationLog===============" + operationLog);
			operationLogDao.save(operationLog);
		} catch (Exception e) {
			logger.error("用户操作日志记录异常", e);
		}
		System.out.println("拦截器postHandle===============================");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {

		System.out.println("---------------拦截器开始------------------");
		try {
			response.setHeader("Content-type", "application/json;charset=UTF-8");
			String requestMethord = request.getRequestURI();
			// 请求方法
			if (requestMethord == null) {
				return false;
			}
			// 获取请求参数
			parameterMap = JSON.parseObject(new BodyReaderHttpServletRequestWrapper(request).getBodyString(request));
			// System.out.println("parameterMap============="+parameterMap.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("拦截器拦截完成");
		return true;
	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
